package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.constant.Constant;
import com.bdqn.pojo.PageSupport;
import com.bdqn.pojo.Record;
import com.bdqn.pojo.Supplier;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.RecordService;
import com.bdqn.service.SupplierService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/**/storageRecord")
public class RecordController {
    private Logger logger = Logger.getLogger(SysUserController.class);
    @Resource
    private RecordService recordService;
    @Resource
    private SupplierService supplierService;


    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "queryGoodsName",required = false) String queryGoodsName,
                       @RequestParam(value = "querySupplierId",required = false) Long querySupplierId,
                       @RequestParam(value = "queryPayStatus",required = false) Integer queryPayStatus){
        List<Record> recordList = null;
        try {
            //设置页面容量
            int pageSize = Constant.pageSize;

            //总数据
            int totalCount = recordService.recordCount(queryGoodsName,querySupplierId,queryPayStatus);

            //总页数
            PageSupport page = new PageSupport();
            page.setPageSize(pageSize);
            page.setCurrentPageNo(pageIndex);
            page.setTotalCount(totalCount);
            //总页数
            int totalPageCount = page.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            recordList = recordService.getRecordList(queryGoodsName,querySupplierId,queryPayStatus,pageIndex,pageSize);
            logger.debug(recordList);
            model.addAttribute("storageRecordList",recordList);
            List<Supplier> supplierList = supplierService.getAllList();
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
            model.addAttribute("queryGoodsName",queryGoodsName);
            model.addAttribute("querySupplierId",querySupplierId);
            model.addAttribute("queryPayStatus",queryPayStatus);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败" + e);

        }
        return "/storageRecord/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        logger.info("进入添加页面");
        List<Supplier> supplierList = supplierService.getAllList();
        model.addAttribute("supplierList",supplierList);
        return "/storageRecord/add";
    }

    @PostMapping("/add")
    public String add(Record record, HttpSession session){
        record.setCreatedUserId(((SysUser)session.getAttribute(Constant.USER_SESSION)).getId());
        record.setCreatedTime(new Date());
        if (recordService.recordAdd(record)){
            return "redirect:/storageRecord/list";
        }
        return "/storageRecord/add";
    }

    /**
     * 视图
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view/{id}")
    //@GetMapping("/{id}")
    //@GetMapping("/{id}/view")
    public String view(@PathVariable String id, Model model) {
        logger.debug("根据Id查询用户详情" + id + "\n");
        Record record = recordService.recordLook(id);
        model.addAttribute("storageRecord",record);
        return "storageRecord/view";
    }

    @RequestMapping("/toUpdate/{storageRecordId}")
    public String toUpdate(@PathVariable String storageRecordId,Model model){
        logger.info("进入修改页面");
        Record storageRecord = recordService.recordLook(storageRecordId);
        List<Supplier> supplierList = supplierService.getAllList();
        logger.info("修改信息：" + storageRecord);
        model.addAttribute("storageRecord",storageRecord);
        model.addAttribute("supplierList",supplierList);
        return "storageRecord/update";
    }

    @PostMapping("/update")
    public String update(Record record,HttpSession session){
        logger.debug("修改供货商信息");
        record.setUpdatedUserId(((SysUser)session.getAttribute(Constant.USER_SESSION)).getId());
        record.setUpdatedTime(new Date());
        logger.debug("入库信息更新后数据：" + record);
        if (recordService.recordUpdate(record)){
            return "redirect:storageRecord/list";
        }
        return "storageRecord/update";
    }

    @ResponseBody
    @RequestMapping("/del/{id}")
    public Object del(@PathVariable String id){
        logger.info("进入删除方法");
        HashMap<String,Object> resultMap = new HashMap<>();
        logger.info("入库信息删除Id：" + id);
        if (recordService.delRecord(Integer.valueOf(id))){
            resultMap.put("delResult","true");
        }else{
            resultMap.put("delResult",false);
        }
        return JSON.toJSONString(resultMap);
    }
}
